﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lamex.mMachine.Common
{
    public sealed class SerialNoHelper
    {
        private static volatile SerialNoHelper helper;
        private static readonly Object syncRoot = new Object();

        private static String lastdate;
        private static Int32 lastno;

        public SerialNoHelper()
        {
        }
        public static SerialNoHelper Helper
        {
            get
            {
                if (helper == null)
                {
                    lock (syncRoot)
                    {
                        if (helper == null)
                            helper = new SerialNoHelper();
                    }
                }
                return helper;
            }
        }
        /// <summary>
        /// 生成流水号
        /// </summary>
        /// <returns></returns>
        public static String Generate()
        {
            lock (syncRoot)
            {
                String serialno = GetSerialNo();
                var today = DateTime.Today.ToString("yyyyMMdd");
                string strchar = "DEV";
            
                if (!String.IsNullOrEmpty(serialno) && serialno.Substring(3, 8) == today)
                    lastno = Convert.ToInt32(serialno.Substring(11));
                else        
                    lastno = 0;    

                return string.Format("{0}{1}{2}", strchar, today, (++lastno).ToString().PadLeft(6, '0'));

            }
        }
        //从数据库读取最大的流水号
        public static string GetSerialNo()
        {
            DataTable dataTable = new DataTable();
            string stringNo = "";
            string sql = @"SELECT top 1 MACHINE_NO  FROM [LamexMESManager].[dbo].[FAMA_Account_Basic_Info]
            order by MACHINE_NO desc";
            dataTable = Lamex.Base.BaseBuildSql.GetDataTableBySql(sql);
            if (dataTable.Rows.Count > 0)
                stringNo = dataTable.Rows[0][0].ToString();
            return stringNo;
        }
    }
}
